# agents/factor_agents/evernight_agent.py
from .base_factor_agent import BaseFactorAgent
from game_engine.game_state import FactorDevelopment, GameWorld
import numpy as np

class EvernightAgent(BaseFactorAgent):
    """长夜月智能体 - 召唤辅助特化 [火种：忘却]"""
    
    def __init__(self, factor: FactorDevelopment, game_world: GameWorld):
        super().__init__(factor, game_world)
        self.personality_traits.update({
            "aggression": 0.3,      # 低攻击性
            "caution": 0.8,         # 高谨慎性
            "memory_manipulation": 0.9,  # 记忆操控
            "support_focus": 0.95   # 辅助专注
        })
        self.memory_echoes = []  # 记忆回响
        self.forgotten_skills = {}  # 被遗忘的技能
        self.last_memory_shift = 0
    
    def make_decision(self, current_time: int) -> str:
        """长夜月的决策逻辑"""
        situation = self.evaluate_situation()
        
        # 记忆操控
        if current_time - self.last_memory_shift > 35:
            self.last_memory_shift = current_time
            return "shift_memories"
        
        # 召唤记忆回响
        if len(self.memory_echoes) < 2 and situation["need_echoes"]:
            echo_type = self._choose_echo_type(situation)
            return f"summon_{echo_type}_echo"
        
        # 辅助盟友记忆
        if situation["confused_allies"]:
            most_confused = max(situation["confused_allies"], 
                              key=lambda x: x["confusion_level"])
            return f"clarify_memory:{most_confused['ally'].name}"
        
        # 干扰敌人记忆
        if situation["vulnerable_enemies"]:
            target = situation["vulnerable_enemies"][0]
            return f"cloud_memory:{target.name}"
        
        # 记忆整理
        return "organize_memories"
    
    def evaluate_situation(self) -> Dict:
        """评估当前局势"""
        nearby_factors = self.get_nearby_factors()
        
        confused_allies = []
        vulnerable_enemies = []
        need_echoes = False
        
        for factor in nearby_factors:
            if not self._is_potential_threat(factor):
                # 判断盟友是否困惑（技能使用效率低）
                confusion_level = self._calculate_confusion(factor)
                if confusion_level > 0.6:
                    confused_allies.append({
                        "ally": factor,
                        "confusion_level": confusion_level
                    })
            else:
                # 判断敌人是否易受记忆攻击
                if (factor.attributes['perception'] < 15 or 
                    len(factor.skills) < 3):  # 技能少可能记忆脆弱
                    vulnerable_enemies.append(factor)
        
        # 需要回响的情况
        total_allies = len([f for f in nearby_factors if not self._is_potential_threat(f)])
        need_echoes = total_allies > 3 and len(self.memory_echoes) < 2
        
        return {
            "confused_allies": confused_allies,
            "vulnerable_enemies": vulnerable_enemies,
            "need_echoes": need_echoes,
            "active_echoes": len(self.memory_echoes),
            "memory_stability": self._calculate_memory_stability()
        }
    
    def _calculate_confusion(self, ally: FactorDevelopment) -> float:
        """计算盟友困惑程度"""
        # 简化计算：基于技能使用频率和效率
        if len(ally.skills) == 0:
            return 0.8  # 没有技能很困惑
        
        # 假设有记忆相关的评估
        recent_actions = [log for log in self.game_world.game_log 
                         if log.get("factor") == ally.name][-5:]
        if len(recent_actions) < 3:
            return 0.3  # 行动不足
        
        # 计算行动一致性
        action_types = [action.get("type", "") for action in recent_actions]
        unique_actions = len(set(action_types))
        consistency = 1 - (unique_actions / len(action_types)) * 0.5
        
        return 1 - consistency  # 不一致性越高越困惑
    
    def _choose_echo_type(self, situation: Dict) -> str:
        """选择回响类型"""
        if situation["confused_allies"]:
            return "clarity"  # 清晰回响
        elif situation["vulnerable_enemies"]:
            return "obscuring"  # 遮蔽回响
        else:
            return "support"  # 支援回响
    
    def _calculate_memory_stability(self) -> float:
        """计算记忆稳定性"""
        base_stability = 0.7
        echo_penalty = len(self.memory_echoes) * 0.1
        time_bonus = min(0.2, (self.game_world.current_time - self.last_memory_shift) / 50)
        
        return max(0.3, base_stability - echo_penalty + time_bonus)